<template>
  <div class="all">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-card class="personNum" style="margin-left:20px">
          <div slot="header" class="clearfix" style="text-align: center;">
            <div> 当前在线人数 {{ onlineNum }} 人</div>
          </div>
          <div v-for="o in onlineList" :key="o" class="text item">
            <div style="cursor: pointer;" @click="getUsername(o)">{{ o }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="20">
        <el-card class="box-card">
          <div slot="header" class="clearfix" style="text-align: center;">
            <span style="text-align: center;">聊天对象({{ chatting }})</span>
            <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>
          </div>

          <div v-for="o in myMessageList" :key="o.content" class="text item">
            <div class="to_avator">   <el-avatar :src="o.avator" /></div>
            <div class="to_message">{{ o.content }}</div>

            <div class="to_time" style="display:inline-block">{{ o.nowTime }}</div>
          </div>
          <!-- <div v-for="o in 0" :key="o" class="text item" style=" right: 15px;  border: 1px solid blue; display: block;">

        <div class="my_message">{{ o.content }}</div>
        <div class="my_avator">
          <el-avatar :src="o.avator" />
        </div>
      </div> -->

        </el-card>
        <div class="bootom">
          <input id="sendMessage" v-model="content" class="sendMessage" @keyup.enter="send">
          <el-button style="position:absolute;right: 0px; bottom: 0px;" @click="send">发送</el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crudChatMessages from '@/api/chatMessages'

import { mapGetters } from 'vuex'
import { getTime } from '@/utils/dateFormat'

export default {

  data() {
    return {
      onlineNum: 0,
      content: null,
      chatting: '',
      myMessageList: [],
      nowTime: getTime(),
      welcomeMessage: '',
      onlineList: []
    }
  },
  computed: {
    ...mapGetters([
      'user',
      'baseApi'

    ])
  },
  mounted() {
    this.initWebSocket()
    // 发送请求给后端获取在线人数和用户列表
    crudChatMessages.getOnlineUsers().then(response => {
      this.onlineNum = response.onlineNum
      this.onlineList = response.onlineList
    }).catch(error => {
      console.error('获取在线用户信息失败: ' + error)
    })
  },
  methods: {

    getUsername(data) {
      this.chatting = data
    },
    initWebSocket() {
      const wsUri = process.env.VUE_APP_WS_API + '/webSocket/' + this.user.username
      this.websock = new WebSocket(wsUri)
      console.log(this.websock)
      this.websock.onerror = this.webSocketOnError
      this.websock.onmessage = this.webSocketOnMessage
    },
    webSocketOnError(e) {
      this.$notify({
        title: 'WebSocket连接发生错误',
        type: 'error',
        duration: 0
      })
    },
    webSocketOnMessage(e) {
      console.log(e)
      console.log('---------')
      if (e.data.indexOf('content') !== -1) {
        var messageObject = JSON.parse(e.data)
        this.myMessageList.push(messageObject)
      } else if (e.data.indexOf('[') !== -1) {
        var str = e.data.slice(1)
        this.onlineList = str.slice(0, str.length - 1).split(',')
        this.onlineNum = this.onlineList.length
      } else {
        this.$message({
          message: '欢迎' + e.data + '加入群聊',
          type: 'success'
        })
      }
    },

    send() {
      if (this.chatting === '') {
        this.$message(
          {
            message: '请选择聊天对象',
            type: 'danger'
          }
        )
      } else {
        var chatObject = {}
        chatObject.type = 'message'
        chatObject.content = this.content
        // chatObject.nowTime = getTime()
        chatObject.sender = this.user.username, // 发送人
        chatObject.receiver = this.chatting // 接收人
        // chatObject.avator = this.baseApi + '/avatar/' + this.user.avatarName

        this.websock.send(JSON.stringify(chatObject))
        this.$message(
          {
            message: '发送成功',
            type: 'success'
          }
        )
        this.content = null
      }
    }
  }

}
</script>

<style >
 .all{
    width: 100%;
    height:500px;
    position: relative;

  }

  .text {
    font-size: 14px;
    margin-top: 5px;

  }

  .item {
    margin-top: 5px;
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";

  }
  .clearfix:after {
    clear: both
  }

  .personNum{
    margin-left: 2%;
    width: 100%;
    height:500px;

  }
  .box-card {
    margin-left: 2%;
    width: 80%;
    height:500px;
    position: relative;
    overflow-y:auto;

  }

  .bootom{
    margin-left: 2%;
    width: 66%;
    border-top: 3px solid grey;
    height: 30%;
    position: absolute;
    bottom: 0px;
  }
  .sendMessage{
    width: 100%;
    height:80%;
  }

 .to_avator, .to_message {
    display: inline-block;
  }
  .to_message{
    font-size: 13px;
    font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
    margin-left: 10px;
  }

  .to_time{
    display: inline-block;
    position: relative;
    left: -90px;
    top: -25px;
  }

  .my_avator, .my_message{
    position: relative;
    display: inline-block;
    left:95%;
    border: 1px solid red;
  }
  .my_avator{

  }

</style>
